// 引入axios
import axios from 'axios';
import {
    userLogout
} from '@/utils'
import { tansParams, blobValidate } from '@/utils/ruoyi'
import {
    ElMessage,
    ElMessageBox,
    ElLoading
} from "element-plus";
let downloadLoadingInstance=null;
import router from '@/router'
// 是否显示重新登录
export let isRelogin = { show: false };

// 创建axios实例
const httpService = axios.create({
    // url前缀-'http:xxx.xxx'
    // baseURL: process.env.BASE_API, // 需自定义
    baseURL: process.env.VUE_APP_WEB_API,
    // 请求超时时间
    timeout: 100 * 1000 // 需自定义
});

//添加请求和响应拦截器
// 添加请求拦截器
httpService.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // console.log(sessionStorage.getItem("token"))
    let token = sessionStorage.getItem("token")
    if (token) {
        config.headers.token = token;
    } else {
        router.push("/login")
    }
    return config;
}, function (error) {
    console.log("error:", error)
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
httpService.interceptors.response.use(function (response) {
    // console.log("response:", response.data)
    if (response.data.code == 500) {
        ElMessage.error(response.data.msg)
    }
    return response;
    // 对响应数据做点什么
}, function (error) {
    // 对响应错误做点什么
    if (error.response && error.response.data) {
        const result = error.response.data;
        if (!isRelogin.show) {
            isRelogin.show = true;
            if (result["code"] == 401) {
                ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    isRelogin.show = false;
                    userLogout()
                }).catch(() => {
                    isRelogin.show = false;
                });
                return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
            }
        }
    }

    return Promise.reject(error);
});

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {}, ) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,

        }).then(response => {
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}
export function exportFile(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            responseType: 'blob'
        }).then(response => {
            resolve(response);
        }).catch(error => {
            console.log(error)
            reject(error);
        });
    });
}

/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}
export function download(url, params, filename, config) {
    downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    return httpService.post(url, params, {
      transformRequest: [(params) => { return tansParams(params) }],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config
    }).then(async (res) => {
        console.log('download',res.data)
        let data=res.data;
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        ElMessage.error(errMsg);
      }
      downloadLoadingInstance.close();
    }).catch((r) => {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close();
    })
  }
export function getServerUrl() {
    return process.env.VUE_APP_WEB_API;
}
export function getWsBaseUrl() {
    return process.env.VUE_APP_WS_API
}
    
export default httpService